package com.aiti.lulian.controller.newCard;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.newCard.CardAdminExportRecordDto;
import com.aiti.lulian.dto.newCard.CardAdminListFieldConfigDto;
import com.aiti.lulian.dto.newCard.CardBaseInfoDto;
import com.aiti.lulian.dto.newCard.CardUserManagementDto;
import com.aiti.lulian.service.CardAdminListFieldConfigService;
import com.aiti.lulian.service.newCard.CardAdminBackendService;
import com.aiti.lulian.vo.CardEnterpriseTemplateVo;
import com.aiti.lulian.vo.newCard.CardMemberDataVo;
import com.aiti.lulian.vo.newCard.CardUserTemplateVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/new-card/admin-backend")
public class CardAdminBackendController extends WebController {

    private static final String USER_AUTHENTICATION_KEY = "user_authentication_sms:%s";

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CardAdminBackendService cardAdminBackendService;
    @Autowired
    private CardAdminListFieldConfigService cardAdminListFieldConfigService;

    @ApiOperation("查询用户管理列表")
    @GetMapping("/page")
    public Message getUserManagementPage(CardUserManagementDto dto) {
        return cardAdminBackendService.getUserManagementPage(dto);
    }

    @ApiOperation("获取当前用户配置好的列表展示字段")
    @GetMapping("/get-list-field")
    public Message getListFieldByUserId(@RequestParam("userId") String userId) {
        return cardAdminListFieldConfigService.getListFieldByUserId(userId);
    }

    @ApiOperation("配置列表展示字段")
    @PutMapping("/config-list-field")
    public Message configListField(@RequestBody CardAdminListFieldConfigDto dto) {
        return cardAdminListFieldConfigService.configListField(dto);
    }

    @ApiOperation("批量导出用户数据")
    @GetMapping("/export-user-data")
    public void exportUserData(HttpServletResponse response, CardUserManagementDto dto) throws IOException {
        cardAdminBackendService.exportUserData(response, dto);
    }

    @ApiOperation("批量编辑用户数据")
    @PutMapping("/update-data-batch")
    public Message updateUserDataBatch(@RequestBody CardUserManagementDto dto) {
        try {
            if (dto.getParamList() == null || dto.getParamList().isEmpty()) {
                return Message.fail("请选择至少一条数据");
            }
            return cardAdminBackendService.updateUserDataBatch(dto);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("批量编辑用户数据失败：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail();
        }
    }

    @ApiOperation("获取企业下全部荣誉资质")
    @GetMapping("/get-all-qualifications")
    public Message getEnterpriseAllQualifications(@RequestParam("enterpriseId") String enterpriseId) {
        return cardAdminBackendService.getEnterpriseAllQualifications(enterpriseId);
    }

    @ApiOperation("获取企业下全部附件")
    @GetMapping("/get-enterprise-all-files")
    public Message getEnterpriseAllFiles(@RequestParam("enterpriseId") String enterpriseId) {
        return cardAdminBackendService.getEnterpriseAllFiles(enterpriseId);
    }

    @ApiOperation("获取个人用户下全部附件")
    @GetMapping("/get-personal-all-files")
    public Message getPersonalAllFiles(@RequestParam("userId") String userId) {
        return cardAdminBackendService.getPersonalAllFiles(userId);
    }

    @ApiOperation("获取模板下个人或企业成员相关数据")
    @GetMapping("/get-member-data-by-template")
    public Message getMemberDataByTemplate(CardBaseInfoDto dto) {
        Page<CardMemberDataVo> page = startPage(dto);
        List<CardMemberDataVo> list = cardAdminBackendService.getMemberDataByTemplate(dto, page);
        return Message.success(getPageResult(list, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    @ApiOperation("获取企业下模板使用情况")
    @GetMapping("/get-template-using-data")
    public Message getEnterpriseTemplateUsingData(CardBaseInfoDto dto) {
        Page<CardEnterpriseTemplateVo> page = startPage(dto);
        List<CardEnterpriseTemplateVo> list = cardAdminBackendService.getTemplateUsingData(dto, page);
        return Message.success(getPageResult(list, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    @ApiOperation("获取个人用户下模板使用情况")
    @GetMapping("/get-personal-template-using-data")
    public Message getPersonalTemplateUsingData(@RequestParam("userId") String userId, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Page<CardUserTemplateVo> page = startPage(pageNum, pageSize);
        List<CardUserTemplateVo> list = cardAdminBackendService.getPersonalTemplateUsingData(userId, page);
        return Message.success(getPageResult(list, pageNum, pageSize, page.getTotal()));
    }

    @ApiOperation("导出模板下个人或企业成员相关数据")
    @GetMapping("/export-member-data-by-template")
    public void exportMemberDataByTemplate(HttpServletResponse response, CardBaseInfoDto dto) throws IOException {
        cardAdminBackendService.exportMemberDataByTemplate(response, dto);
    }

    @ApiOperation("变更管理员账号")
    @PutMapping("/change-admin-account")
    public Message changeAdminAccount(@RequestBody CardUserManagementDto dto) {
        if (StrUtil.isBlank(dto.getEnterpriseId())) {
            return Message.fail("企业信息无效");
        }
        if (StrUtil.isBlank(dto.getNewAdminAccount())) {
            return Message.fail("请填写转让后的管理员账号");
        }
        if (dto.getChangeMode() == null) {
            return Message.fail("请选择变更模式");
        }
        if (!(dto.getChangeMode() == 1 || dto.getChangeMode() == 2)) {
            return Message.fail("变更模式选择无效");
        }
        // 如果传了手机验证码，则须对验证码的正确性进行校验
        if (StrUtil.isNotEmpty(dto.getCode())) {
            // 构建 RedisKey
            String key = String.format(USER_AUTHENTICATION_KEY, dto.getNewAdminAccount());
            // 取出 Redis 中的验证码
            String recordCode = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isEmpty(recordCode)) {
                return Message.fail("验证码已过期");
            }
            if (!dto.getCode().equals(recordCode)) {
                return Message.fail("验证码错误");
            }
        }
        return cardAdminBackendService.changeAdminAccount(dto);
    }

    @ApiOperation("获取企业特权详情")
    @GetMapping("/get-enterprise-privileges")
    public Message getEnterprisePrivileges(@RequestParam("enterpriseId") String enterpriseId) {
        return Message.success(cardAdminBackendService.getEnterprisePrivileges(enterpriseId));
    }

    @ApiOperation("企业特权变更")
    @PutMapping("/change-enterprise-privileges")
    public Message changeEnterprisePrivileges(@RequestBody CardUserManagementDto dto) {
        try {
            if (StrUtil.isBlank(dto.getEnterpriseId())) {
                return Message.fail("企业信息无效");
            }
            if (StrUtil.isNotBlank(dto.getVersion())) {
                String[] miniProgramVersionList = {"1", "2", "3", "4", "5"};
                List<String> list = Arrays.asList(miniProgramVersionList);
                if (!list.contains(dto.getVersion())) {
                    return Message.fail("开通版本选择无效");
                }
            }
            if (StrUtil.isNotBlank(dto.getQualificationRecognitionType()) &&
                    !("1".equals(dto.getQualificationRecognitionType()) || "2".equals(dto.getQualificationRecognitionType()))) {
                return Message.fail("资质认定类型选择无效");
            }
            return cardAdminBackendService.changeEnterprisePrivileges(dto);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("企业特权变更失败：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail();
        }
    }

    @ApiOperation("新增导出记录")
    @PostMapping("/exportRecord")
    public Message addExportRecord(@RequestBody CardAdminExportRecordDto dto) {
        cardAdminBackendService.addExportRecord(dto);
        return Message.success("记录成功");
    }
}
